// pages/group/group.js
var common = require("../../common/common.js").common;

var QQMapWX = require("../../sdk/qqmap-wx-jssdk.min.js");

var util = require("../../utils/util.js");

var qqmapsdk;

Page({
    /**
   * 页面的初始数据
   */
    data: {
        array: [ "女", "男", "保密" ],
        sex_value: "",
        multiArrName: [],
        multiList_value: "0",
        index: 0,
        region: [ "江苏省", "南通市", "崇川区" ],
        address_value: "",
        info: {},
        rec_leader_id: "",
        latitude: "31.997012",
        longitude: "120.861111",
        chooseAddress: "",
        color_header: "",
        color_main: "",
        color_minor: "",
        multiUniacid: "-1",
        showInfoTip: false,
        //授权失败的弹框
        tmplIds: [],
        //模板消息tmplIds
        subscribeMessage: true,
        leader_area_id: ""
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        common.getAppBase().then(() => {
            qqmapsdk = new QQMapWX({
                key: that.data.appBase.location_key
            });
        });
        this.getBase();
        var that = this;
        //区域团长分享
                if (options.leader_area_id) {
            that.setData({
                leader_area_id: options.leader_area_id
            });
        }
        that.getdata();
        that.getMulti();
        wx.getLocation({
            type: "wgs84",
            success(res) {
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            }
        });
        that.getTmplIds();
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        var that = this;
        setTimeout(() => {
            wx.getLocation({
                type: "wgs84",
                success: function(res) {
                    that.setData({
                        showInfoTip: false
                    });
                },
                fail: function(res) {
                    that.setData({
                        showInfoTip: true
                    });
                }
            });
        }, 500);
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    continueGetSet: function() {
        let that = this;
        wx.getSetting({
            success(res) {}
        });
        wx.openSetting({
            success(res) {
                if (res.authSetting["scope.userInfo"] && res.authSetting["scope.userLocation"]) {
                    that.setData({
                        showInfoTip: false
                    });
                }
            }
        });
    },
    //获取tmplIds
    getTmplIds: function() {
        let that = this;
        const version = wx.getSystemInfoSync().SDKVersion;
        if (util.compareVersion(version, "2.8.2") < 0) {
            that.setData({
                tmplIds: [],
                subscribeMessage: false
            });
            return;
        }
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if (v.type == "32") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    },
    // 性别选择
    bindPickerChange: function(e) {
        this.setData({
            sex_value: e.detail.value
        });
    },
    multiChange: function(e) {
        this.setData({
            multiList_value: e.detail.value,
            multiUniacid: this.data.multiArrUniacid[e.detail.value]
        });
    },
    // 选择省市区函数
    changeRegin(e) {
        this.setData({
            address_value: e.detail.value
        });
    },
    getdata: function() {
        var openid = wx.getStorageSync("user").openid;
        var that = this;
        common.request({
            endpoint: "Leader/leaderapply/leader_detail",
            method: "post",
            data: {
                openid: openid
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                if (res.extra.can_apply == 0) {
                    //不可申请团长，需要购买指定商品后，方可申请团长
                    var detailInfo = res.extra;
                    wx.showModal({
                        title: "提示",
                        content: detailInfo.condition_msg,
                        success(res) {
                            if (res.confirm) {
                                if (detailInfo.pro_id) {
                                    wx.navigateTo({
                                        url: "/pages/pro_detail/pro_detail?id=" + detailInfo.pro_id
                                    });
                                } else {
                                    wx.navigateBack({});
                                }
                            } else if (res.cancel) {
                                wx.navigateBack({});
                            }
                        }
                    });
                } else {
                    if (res.extra.sex != 0 && res.extra.sex != 1 && res.extra.sex != 2) {
                        that.setData({
                            info: res.extra,
                            sex_value: 2,
                            address_value: res.extra.address_name
                        });
                    }
                    that.setData({
                        info: res.extra,
                        address_value: res.extra.address_name
                    });
                }
            }
        });
    },
    //获取加盟商
    getMulti: function() {
        var that = this;
        var code = that.data.code;
        common.request({
            endpoint: "wx/city_list",
            method: "post",
            data: {
                leader_id: wx.getStorageSync("rec_leader_id")
            },
            header: {},
            success: function(res) {
                // if (res.extra.length > 1) {
                var multiArrName = [ "请点击此处选择！" ];
                var multiArrUniacid = [ "-1" ];
                for (var i = 0; i < res.extra.length; i++) {
                    var arr = res.extra[i];
                    multiArrName.push(arr["name"]);
                }
                for (var i = 0; i < res.extra.length; i++) {
                    var arr = res.extra[i];
                    multiArrUniacid.push(arr["uniacid"]);
                }
                that.setData({
                    multiArrName: multiArrName,
                    multiArrUniacid: multiArrUniacid
                });
                if (res.extra.length == 1) {
                    that.setData({
                        multiList_value: 1,
                        multiUniacid: res.extra[0].uniacid
                    });
                }
            }
        });
    },
    formSubmit: function() {
        let that = this;
        that.formSubmit_ch();
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {}
            });
        }
    },
    formSubmit_ch: function() {
        var openid = wx.getStorageSync("user").openid;
        var that = this;
        var community = that.data.communityName;
        var rec_leader_id = "";
        if (wx.getStorageSync("rec_leader_id")) {
            rec_leader_id = wx.getStorageSync("rec_leader_id");
        }
        //   //选择加盟商
                if (that.data.multiArrName.length > 1) {
            if (that.data.multiUniacid == "-1") {
                wx.showModal({
                    title: "提示",
                    content: "请选择城市或加盟商"
                });
                return false;
            }
        }
        if (that.data.info.name == "") {
            wx.showModal({
                title: "提示",
                content: "姓名不能为空"
            });
            return false;
        }
        if (that.data.info.phone == "") {
            wx.showModal({
                title: "提示",
                content: "手机号码不能为空"
            });
            return false;
        }
        var reg2 = /^[1][0-9][0-9]{9}$/;
        if (!reg2.test(that.data.info.phone)) {
            wx.showModal({
                title: "提示",
                content: "请填写正确手机号"
            });
            return false;
        }
        if (that.data.chooseAddress == "") {
            wx.showModal({
                title: "提示",
                content: "地址" + community + "不能为空"
            });
            return false;
        }
        if (that.data.info.address_other == "" || that.data.info.address_other == null) {
            wx.showModal({
                title: "提示",
                content: "地址不能为空"
            });
            return false;
        }
        // var res3 = /^[1-9]\d*|0$/
        // if (!res3.test(that.data.info.distribution_fee)) {
        //   wx.showModal({
        //     title: '提示',
        //     content: that.data.leaderName + '配送价必须为整数',
        //   })
        //   return false;
        // }
                common.request({
            endpoint: "Leader/leaderapply/edit_leader_detail",
            method: "post",
            data: {
                openid: openid,
                info: {
                    address_name: [ that.data.address_value[0], that.data.address_value[1], that.data.address_value[2] ],
                    address_other: that.data.info.address_other,
                    area: that.data.chooseAddress,
                    distribution_fee: "5",
                    img: that.data.info.img,
                    lati: that.data.latitude + "," + that.data.longitude,
                    name: that.data.info.name,
                    new_uniacid: that.data.multiUniacid,
                    nickname: that.data.info.nickname,
                    phone: that.data.info.phone,
                    remark: that.data.info.remark,
                    leader_wx: that.data.info.weixin,
                    sex: that.data.sex_value
                },
                rec_leader_id: rec_leader_id,
                leader_area_id: that.data.leader_area_id
            },
            header: {
                "content-type": "application/json"
            },
            success: res => {
                wx.showToast({
                    title: "提交成功",
                    // content: '提交成功，请耐心等待！',
                    icon: "success",
                    success: res => {
                        setTimeout(() => {
                            wx.reLaunch({
                                url: "/pages/personal/personal"
                            });
                        }, 500);
                    }
                });
            },
            fail: res => {
                wx.showModal({
                    title: "提示",
                    content: "申请失败," + res.message,
                    success: res => {
                        setTimeout(() => {
                            wx.navigateTo({
                                url: "/pages/personal/personal"
                            });
                        }, 500);
                    }
                });
            }
        });
    },
    onChangeAddress: function() {
        var that = this;
        wx.chooseLocation({
            success: function(res) {
                that.setData({
                    chooseAddress: res.name,
                    latitude: res.latitude,
                    longitude: res.longitude
                });
                that.getLocal(res.latitude, res.longitude);
            },
            fail: function(err) {}
        });
    },
    /** 
   * 记录 input 的值 
   * e: object 
   */
    recordValue: function(e) {
        let key = "info." + e.currentTarget.dataset.name;
        let value = e.detail.value;
        this.setData({
            [key]: value
        });
    },
    getBase: function() {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                wx.setNavigationBarColor({
                    frontColor: "#ffffff",
                    backgroundColor: res.extra.color_main
                });
                wx.setNavigationBarTitle({
                    title: "填写申请资料"
                });
                that.setData({
                    color_header: res.extra.color_header,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    leader_share: res.extra.leader_share,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    communityName: res.extra.community_title ? res.extra.community_title : "社区",
                    leader_apply_display: res.extra.leader_apply_display
                });
                if (res.extra.leader_apply_display == 0) {
                    wx.showModal({
                        title: "提示",
                        content: "该功能暂未开放，请返回首页",
                        complete: function(res) {
                            wx.switchTab({
                                url: "/pages/index/index"
                            });
                        }
                    });
                }
            }
        });
    },
    getLocal: function(latitude, longitude) {
        let that = this;
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success: function(res) {
                let province = res.result.ad_info.province;
                let city = res.result.ad_info.city;
                let district = res.result.ad_info.district;
                that.setData({
                    address_value: [ province, city, district ]
                });
            },
            fail: function(res) {},
            complete: function(res) {}
        });
    }
});